<?php

namespace App\Admin\Controllers;

use App\AdminUser;
use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Maatwebsite\Excel\Facades\Excel; 

class UserController extends Controller
{
	/**
	 * [index 列表]
	 * @return [type] [description]
	 */
	public function index(Request $request)
	{
		$users = AdminUser::where('status', '=', 1);
		if ($request->input('keywords')) {
			$users->where('name', 'like', '%' . $request->input('keywords') . '%');
		}
		$users = $users->paginate(10);
		$users = $users->appends([
				'keywords' => $request->input('keywords')
			]);
		
		return view('/admin/user/index', compact('users'));
	}

	/**
	 * [store 创建操作]
	 * @return [type] [description]
	 */
	public function store(Request $request)
	{
        $validator = Validator::make($request->all(), [
			'name' => 'required',
			'password' => 'required'
        ], [
        	'name.required' => '请填写用户名',
        	'password.required' => '请填写密码'
        	]);

        if ($validator->passes()) {
			$name = $request->input('name');
			$password = bcrypt($request->input('password'));
			AdminUser::create(compact('name', 'password'));

	    	return redirect('/admin/users/');
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }	
	}

	/**
	 * [create 创建页]
	 * @return [type] [description]
	 */
	public function create()
	{
		return view('/admin/user/create');
	}

	/**
	 * [role 用户角色]
	 * @return [type] [description]
	 */
	public function role(\App\AdminUser $user)
	{
		$roles = \App\AdminRole::all();
		$myRoles = $user->roles;
		return view('/admin/user/role', compact('myRoles', 'user', 'roles'));
	}

	/**
	 * [storeRole 储存]
	 * @return [type] [description]
	 */
	public function storeRole(AdminUser $user)
	{
		$this->validate(request(), [
				'roles' => 'required'
			]);
		$roles = \App\AdminRole::findMany(request('roles'));
		$myRoles = $user->roles;
		/*要增加的*/
		$addRoles = $roles->diff($myRoles);
		foreach ($addRoles as $role) {
			$user->assignRole($role);
		}
		/*要删除的*/
		$deleteRoles = $myRoles->diff($roles);
		foreach ($deleteRoles as $role) {
			$user->deleteRole($role);
		}

		return redirect('/admin/users');
	}

	/**
	 * [delete description]
	 * @param  AdminUser $user [description]
	 * @return [type]          [description]
	 */
	public function delete(AdminUser $user)
	{
		$user->update(['status' => 0]);
		return [
			'flag' => true,
			'msg' => '',
			'user_id' => $user->id
		];
	}

	/**
	 * [batchDelete description]
	 * @return [type] [description]
	 */
	public function batchDelete(Request $request)
	{	
		if ($request->input('data')) {
			AdminUser::whereIn('id', $request->input('data'))->update(['status' => 0]);

			return [
				'flag' => true,
				'msg' => '',
				'user_id' => $request->input('data')
			];
		} else {
			return [
				'flag' => false,
				'msg' => '请选择用户'
			];
		}
	}
}